﻿<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="../css/bootstrap.min.css" rel="stylesheet" />
<link href="../font-awesome/css/font-awesome.css" rel="stylesheet" />
<link href="../js/plugins/layer/skin/layer.css" rel="stylesheet" />
<link href="../js/plugins/layer/skin/layer.ext.css" rel="stylesheet" />
<link href="../css/jqgrid/ui.jqgrid.css" rel="stylesheet" />
<link href="../css/style.min.css" rel="stylesheet" />
<script src="../js/jquery-2.1.1.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/plugins/peity/jquery.peity.min.js"></script>
<script src="../js/plugins/jqgrid/jquery.jqGrid.min.js"></script>
<script src="../js/plugins/jqgrid/i18n/grid.locale-cn.js"></script>
<script src="../js/plugins/layer/layer.min.js"></script>
<script src="../js/xlsx.full.min.js"></script>
<script src="../js/plugins/linq/linq.js"></script>
<style>
	.container {
		margin: 10px
	}
	
	.form-control {
		display: initial;
		width: auto;
		margin-right: 10px;
		padding: 0px;
		height: 25px
	}
	
	.pull-right {
		margin-right: 5px
	}
	
	#search-Provice,
	#search-City,
	#search-Part,
	#shopStr {
		max-width: 150px
	}
	.form-control{
    		display: inline-block;
    	}
</style>
<html>

	<head>
		<title>店铺权限维护</title>
	</head>

	<body>
		<div class="container" style="margin-top: 5px">
			<div class="row clearfix firstDiv">
				<label>筛选条件</label>
			</div>
			<div class="row clearfix secondDiv">
				<div class="col-sm-9 column">
					<label>省:</label>&nbsp&nbsp
					<select class="form-control" id="search-Provice">
						<option value="">请选择</option>
					</select>
					<label>市:</label>&nbsp&nbsp
					<select class="form-control" id="search-City">
						<option value="">请选择</option>
					</select>
					<label>输入店铺:</label>&nbsp&nbsp
					<input id="shopStr" type="text" data-projectcode="" class="form-control" />
					<label>陈列师:</label>&nbsp&nbsp
					<select class="form-control" id="search-Part">
						<option value="">请选择</option>
					</select>
				</div>
				<div class="col-sm-3 column">
					<button type="button" class="btn btn-sm btn-primary m-t-n-xs pull-right" id="import-Btn">导入</button>
					<button type="button" class="btn btn-sm btn-primary m-t-n-xs pull-right" id="search-Btn">查询</button>
					<button type="button" class="btn btn-sm btn-danger m-t-n-xs pull-right" id="delete-Btn">删除</button>
					<input type="file" style="display: none" hidden="hidden" id="file-Btn" onunload='console.log("hi")' onchange="importf(this)">
				</div>
			</div>
			<div class="row clearfix thridDiv">
				<label>店铺列表(导入已有店铺时数据会覆盖原来的)</label>
			</div>
			<div class="row clearfix">
				<div class="jqGrid_wrapper">
					<table id="shopTable">
					</table>
					<div id="pager_shopTable"></div>
				</div>
			</div>
		</div>
	</body>

</html>
<script>
	var proviceName = "";
	var cityName = "";
	var shopStr = "";
	var partName = "";

	$(function() {
		$.jgrid.defaults.styleUI = "Bootstrap";

		$("#shopTable").jqGrid({
			datatype: "local",
			height: 700,
			rowNum: 100,
			altRows: true,
			altclass: 'altRowsColour',
			width: ($(".container").parents("html").width() - 20),
			autowidth: false,
			shrinkToFit: true,
			colNames: [" ", "店铺简称", "店铺代码", "开业时间", "省/市", "零售分部", "陈列师", "店经理", "店铺状态"],
			colModel: [{
					name: "checkItem",
					index: "checkItem",
					width: 50,
					align: "center",
				},
				{
					name: "ShopName",
					index: "ShopName",
					//width: 150,
					align: "center",
				},
				{
					name: "ShopCode",
					index: "ShopCode",
					//width: 60,
					align: "center",
				},
				{
					name: "OpenDate",
					index: "OpenDate",
					//width: 60,
					align: "center",
					sorttype: "date",
					formatter: "date"
				},
				{
					name: "Area",
					index: "Area",
					//width: 60,
					align: "center",
				},
				{
					name: "OperatorAreaName",
					index: "OperatorAreaName",
					//width: 60,
					align: "center",
				},
				{
					name: "Display",
					index: "Display",
					//width: 60,
					align: "center",
				},
				{
                    name: "ShopManager",
                    index: "ShopManager",
					//width: 60,
					align: "center",
				},
				{
					name: "ShopState",
					index: "ShopState",
					//width: 60,
					align: "center",
				}
			],
			pager: "#pager_shopTable",
			viewrecords: true,
			hidegrid: false
		});

		$("#import-Btn").on("click", function() {
			$("#file-Btn").click();
		});

		loadList();

		$(window).resize(function() {
			var height = $(".container").parents("html").height() -
				$(".firstDiv").height() -
				$(".secondDiv").height() -
				$(".thridDiv").height() - 90;
			//重新计算容器高度
			var width = ($(".container").parents("html").width() - 20);
			$("#shopTable").setGridHeight(height);
			$("#shopTable").setGridWidth(width);
			$(".container .secondDiv").width(width);
			var colWidth = $(".container .secondDiv .col-sm-9").width() * 0.15;
			$("#search-Provice").width(colWidth);
			$("#search-City").width(colWidth);
			$("#search-Part").width(colWidth);
			$("#shopStr").width(colWidth);
		});

		var areaJson = {};
		//加载地区
		var loadAreaList = function() {
			var s = layer.load(0, {
				shade: [0.2, '#fff'] //0.1透明度的白色背景
			});
			$.post("TaskHandler.ashx", {
					"action": "GetShopAreaList",
				},
				function(data) {
					var sProvice = $("#search-Provice");
					if(data.Success == true) {
						var sHtml = "";
						areaJson = data.Data;
						data.Data.map(function(item, i) {
							sHtml += '<option value=' + item.AreaName + '>' + item.AreaName + '</option>';
						});
						sProvice.append(sHtml);
					}
					layer.close(s);
				});
		}
		loadAreaList();

		var loadPartList = function() {
			var s = layer.load(0, {
				shade: [0.2, '#fff'] //0.1透明度的白色背景
			});
			$.post("TaskHandler.ashx", {
					"action": "GetDisplayList",
				},
				function(data) {
					
					var sPart = $("#search-Part");
					if(data.Success == true) {
						var sHtml = "";
						data.Data.map(function(item, i) {
							sHtml += '<option value=' + item + '>' + item + '</option>';
						});
						sPart.append(sHtml);
					}
					layer.close(s);
				});
		}

		loadPartList();

		$("#search-Provice").change(function() {
			var sCity = $("#search-City");
			var areaName = $(this).children('option:selected').val();
			var childrenList = Enumerable.From(areaJson).Where("d=>d.AreaName=='" + areaName + "'").First();
			var cHtml = "<option value=''>请选择</option>";
			childrenList.child.map(function(child, i) {
				cHtml += '<option value=' + child.AreaName + '>' + child.AreaName + '</option>';
			});
			sCity.empty();
			sCity.append(cHtml);
		});
		//查询
		$("#search-Btn").on("click", function() {
			var e = window.event || event;
			proviceName = $("#search-Provice").find("option:selected").text();
			cityName = $("#search-City").find("option:selected").text();
			shopStr = $("#shopStr").val();
			partName = $("#search-Part").find("option:selected").text();
			if(proviceName == "请选择") {
				proviceName = "";
			}
			if(cityName == "请选择") {
				cityName = "";
			}
			if (partName == "请选择") {
			    partName = "";
			}
			loadList();
		});

		$("#delete-Btn").on("click", function() {
			var e = window.event || event;
			var checkList = $(".checkItem:checked");
			var newList = [];
			checkList.map(function(i, checkItem) {
				newList.push($(checkItem).attr("data-id"));
			});
			$.post("TaskHandler.ashx", {
					"action": "DeleteShopPermissions",
					"jsonData": JSON.stringify(newList),
				},
				function(data) {
					if(data.Success == true) {
						proviceName = "";
						cityName = "";
						shopStr = "";
						partName = "";
						loadList();
						layer.alert('删除成功！', {
							icon: 1,
							skin: 'layer-ext-moon' //该皮肤由layer.seaning.com友情扩展。关于皮肤的扩展规则，去这里查阅
						});
					} else {
						layer.alert(data.Message, {
							icon: 1,
							skin: 'layer-ext-moon' //该皮肤由layer.seaning.com友情扩展。关于皮肤的扩展规则，去这里查阅
						});
					}
					layer.close(s);
				});
		});
        
        
	});

	function loadList() {
		var s = layer.load(0, {
			shade: [0.2, '#fff'] //0.1透明度的白色背景
		});
		$.post("TaskHandler.ashx", {
				"action": "GetShopPermissionsList",
				"proviceName": proviceName,
				"areaName": cityName,
				"shopStr": shopStr,
				"partName": partName,
			},
			function(data) {
				
				if(data.Success == true) {
					
					$("#shopTable").jqGrid('clearGridData');
					var length = data.Data.length;
					if(length > 0) {
						var jsonData = [];
						data.Data.map(function(item, i) {
							var newData = {
								"checkItem": "<input type='checkbox' name='' data-id='" + item.ID + "' class='checkItem'>",
								"ShopName": item.ShopName,
								"ShopCode": item.ShopCode,
								"OpenDate": item.OpenDate,
								"Area": item.ProvinceName + "/" + item.AreaName,
								"OperatorAreaName": item.OperatorAreaName,
								"Display": item.Display,
                                "ShopManager": item.ShopManager,
								"ShopState": item.ShopState
							}
							jsonData.push(newData);
						});
						var height = $(".container").parents("html").height() -
							$(".firstDiv").height() -
							$(".secondDiv").height() -
							$(".thridDiv").height() - 90;
						$("#shopTable").jqGrid('setGridParam', {
							height: height,
							datatype: 'local',
							data: jsonData,
							rowNum: 100,
							pager: "#pager_shopTable",
						}).trigger("reloadGrid");
						addTableClass();
					}
				}
				layer.close(s);
				$("tr").slice(1).click(function() {
				// 切换样式
//				$(this).toggleClass("tr_active");
				// 找到checkbox对象
				var chks = $("input[type='checkbox']", this);
				var tag = $(this).attr("tag");
				if(tag == "selected") {
					// 之前已选中，设置为未选中
					$(this).attr("tag", "");
					chks.prop("checked", false);
				} else {
					// 之前未选中，设置为选中
					$(this).attr("tag", "selected");
					chks.prop("checked", true);
				}
			});
			});
	}

	function addTableClass() {
		$("#shopTable").addClass("ui-common-table");
		$("#shopTable").addClass("table-bordered");
		$("#shopTable").addClass("table-striped");
		$(".ui-jqgrid-htable").addClass("ui-common-table");
		$(".ui-jqgrid-htable").addClass("table-bordered");
		$("#first_pager_shopTable span").addClass("glyphicon");
		$("#first_pager_shopTable span").addClass("glyphicon-step-backward");
		$("#prev_pager_shopTable span").addClass("glyphicon");
		$("#prev_pager_shopTable span").addClass("glyphicon-chevron-left");
		$("#next_pager_shopTable span").addClass("glyphicon");
		$("#next_pager_shopTable span").addClass("glyphicon-chevron-right");
		$("#last_pager_shopTable span").addClass("glyphicon");
		$("#last_pager_shopTable span").addClass("glyphicon-step-forward");
		$("#gview_shopTable th").css("text-align", "center");
		$("#gview_shopTable thead>tr").css("height", "30px");
		var width = ($(".container").parents("html").width() - 20);
		$(".container .secondDiv").width(width);
		var colWidth = $(".container .secondDiv .col-sm-9").width() * 0.15;
		$("#search-Provice").width(colWidth);
		$("#search-City").width(colWidth);
		$("#search-Part").width(colWidth);
		$("#shopStr").width(colWidth);
	}

	/*
	    FileReader共有4种读取方法：
	    1.readAsArrayBuffer(file)：将文件读取为ArrayBuffer。
	    2.readAsBinaryString(file)：将文件读取为二进制字符串
	    3.readAsDataURL(file)：将文件读取为Data URL
	    4.readAsText(file, [encoding])：将文件读取为文本，encoding缺省值为'UTF-8'
	                 */
	var wb; //读取完成的数据
	var rABS = false; //是否将文件读取为二进制字符串

	function importf(obj) { //导入
		if(!obj.files) {

			return;
		}
		var f = obj.files[0];
		var reader = new FileReader();
		reader.onload = function (e) {
		    var data = e.target.result;
			if(rABS) {
				wb = XLSX.read(btoa(fixdata(data)), { //手动转化
					type: 'base64'
				});
			} else {
				wb = XLSX.read(data, {
					type: 'binary'
				});
			}
			//wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
			//wb.Sheets[Sheet名]获取第一个Sheet的数据
			var jsonData = JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]));
			var newData = replaceData(jsonData);
			importToDB(newData);
			$("#file-Btn").val("");
		};
		if (!FileReader.prototype.readAsBinaryString) {
		    rABS = true;;
		}
		else {
		    rABS = false;;
		}

		if (rABS) {
			reader.readAsArrayBuffer(f);
		} else {
		    reader.readAsBinaryString(f);
		}
	}

	function importToDB(data) {
		var s = layer.msg('加载中', {
			icon: 16,
			shade:  [0.3, '#393D49']
		});
		$.post("TaskHandler.ashx", {
				"action": "ImportShopPermissionsList",
				"jsonData": data,
			},
			function(data) {
				if(data.Success == true) {
					layer.alert('导入成功！', {
						icon: 1,
						skin: 'layer-ext-moon' //该皮肤由layer.seaning.com友情扩展。关于皮肤的扩展规则，去这里查阅
					});
					loadList();
				} else {
					layer.alert(data.Message, {
						icon: 1,
						skin: 'layer-ext-moon' //该皮肤由layer.seaning.com友情扩展。关于皮肤的扩展规则，去这里查阅
					});
				}
				layer.close(s);
			});
	}

	function fixdata(data) { //文件流转BinaryString
		var o = "",
			l = 0,
			w = 10240;
		for(; l < data.byteLength / w; ++l)
			o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
		o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
		return o;
	}

	function replaceData(data) {
		if(isContains(data, '"序号"')) {
			data = data.replace(/"序号"/g, '"Num"');
		}
		if(isContains(data, '"店铺简称"')) {
			data = data.replace(/"店铺简称"/g, '"ShopName"');
		}
		if(isContains(data, '"店铺代码"')) {
			data = data.replace(/"店铺代码"/g, '"ShopCode"');
		}
		if(isContains(data, '"开业时间"')) {
			data = data.replace(/"开业时间"/g, '"OpenDate"');
		}
		if(isContains(data, '"城市"')) {
			data = data.replace(/"城市"/g, '"AreaName"');
		}
		if(isContains(data, '"省份"')) {
			data = data.replace(/"省份"/g, '"ProvinceName"');
		}
		if(isContains(data, '"零售分部"')) {
			data = data.replace(/"零售分部"/g, '"OperatorAreaName"');
		}
		if(isContains(data, '"陈列师"')) {
			data = data.replace(/"陈列师"/g, '"Display"');
		}
        if (isContains(data, '"店经理"')) {
            data = data.replace(/"店经理"/g, '"ShopManager"');
		}
		if(isContains(data, '"店铺状态"')) {
			data = data.replace(/"店铺状态"/g, '"ShopState"');
		}
		return data;
	}

	function isContains(str, substr) {
		return str.indexOf(substr) >= 0;
	}
</script>